<template>
    <view class="content">
		<view class="balance-sticky" :class="[{ active : isShowSticky}]">
			<view class="left">
			   <view class="cash">
				    <text class="text">恭喜您获得</text>
					<count-up :num="random" color="#ffffff" width="28" height="44" fontSize="44" fontWeight="400"></count-up>
				    件商品折上再减
				</view>
			</view>
			<button class="share" open-type="share" hover-class="none">
				<text class="iconfont icon-tuanduicankaoxian-"></text>
				分享好友
			</button>
		</view>
		<view class="header">
			<view class="title-share">
				<text class="title">恭喜您获得</text>
				<button class="share" open-type="share" hover-class="none">
					<text class="iconfont icon-tuanduicankaoxian-"></text>
					分享好友
				</button>
			</view>
			<view class="amount-time">
				<view class="left">
					<count-up :num="random" color="#ffffff" width="50" height="80" fontSize="80"></count-up>
					件商品折上再减
				</view>
			</view>
		</view>
        <goods-tab ref="tab" :stickyTop="112" @tabChange="tabChangeCustom" :list="tabList"></goods-tab>

        <view class="goods-list" @touchstart="touchStart" @touchend="touchEnd">
			<million-item
				v-for="(item, index) in tabList[active].list"
				:millionItem="item"
				:index="index"
				:tabIndex="active"
				:key="item.gid"
				@onCopySuccess="onCopySuccess"
				@insBalance="$refs.balancePopup.open()"
			></million-item>
			
			<!-- 商品骨架 -->
			<template v-for="i in ['a', 'b', 'c', 'd']">
				<view class="skeleton-wrap" v-if="
					tabList[active].list.length === 0 &&
					!tabList[active].finished &&
					!tabList[active].empty">
					<skeleton class="goods-skeleton" :loading="true" avatarShape="square" :row="4" avatarSize="254rpx"></skeleton>
				</view>
			</template>
        </view>

		<!-- 加载中插件 -->
		<view class="load-status">
			<load-more status="loading" color="#c6c6c6" iconType="circle" v-if="!tabList[active].finished && !tabList[active].empty"
				:contentText="contentText"></load-more>
			<load-more status="noMore" color="#c6c6c6" v-if="tabList[active].finished" :contentText="contentText"></load-more>
			<empty v-if="tabList[active].empty"></empty>
		</view>

		<!-- 回到顶部 -->
		<view class="scrollTop" :class="[{ show: isShowScrollTop }]" @tap="backTop">
			<text class="iconfont icon-huidaodingbu"></text>
		</view>
		
		<!-- 余额不足弹窗 -->
		<popup ref="balancePopup" type="bottom" @touchmove.stop.prevent>
			<view class="balance-popup">
				<text class="iconfont icon-guanbi" @tap="$refs.balancePopup.close()"></text>
				<view class="title">当前余额不足</view>
				<view class="money">余额：{{ userInfo.subsidiesAmount }}元</view>
				<button class="btn share" open-type="share" hover-class="none" v-if="userInfo.remaining > 0">
					分享好友，再刮1次
				</button>
				<view class="btn do" v-else @click="$refs.balancePopup.close()">我知道了</view>
			</view>
		</popup>
    </view>
</template>

<script>
    import GoodsTab from '@/components/GoodsTab';
    import Empty from "@/components/Empty";
    import MillionItem from "@/components/MillionItem";
    import Skeleton from '@/components/uni/Skeleton';
    import LoadMore from "@/components/uni/LoadMore";
    import CountDown from "@/components/uni/CountDown";
    import CountUp from "@/components/uni/CountUp";
	import Popup from '@/components/uni/Popup';
    import loader from '@/utils/mixin/loader';
    import moment from '@/utils/packges/moment';
    import { mapGetters } from 'vuex';
    export default {
        name: "index",
        mixins: [loader],
        components: {
            GoodsTab,
            LoadMore,
			CountDown,
            Empty,
			MillionItem,
            Skeleton,
			CountUp,
			Popup
        },
        data() {
            return {
                scrollTop: 0,
				couponTime: [],
				startCoor: 0,
				isFirstEnter: false,
				random: 1000
            }
        },
        async onLoad(options) {
			if (!this.hdyxRiskSetting.goldAmount) {
				// 获取风控配置
				this.$store.dispatch('getHdyxRiskSetting');
			}
			uni.hideTabBarRedDot({ index: 1 });
			
			this.random = Math.floor(Math.random() * (1000 - 1500) + 1500);
			
			// 获取百亿补贴用户信息
			if (!uni.getStorageSync('token')) {
				await this.$service.million.bwbtUser.getUserToken().then(async res => {
					await this.$store.commit('SET_TOKEN', res.token);
					await this.$store.dispatch('getUserInfo');
					this.$store.dispatch('addVisitRecordZfb', { pageType : 5 });
				});
			} else {
				await this.$store.dispatch('getUserInfo');
				this.$store.dispatch('addVisitRecordZfb', { pageType : 5 });
			}
			
			if (Number(this.userInfo.subsidiesAmount) === 0 && this.hdyxRiskSetting.shareIconDisplay === 1) {
			    this.$service.million.winners
			        .getSubsidiesAmount({
			            isBybt: true
			        })
			        .then(res => {
			            uni.showToast({
			                title: `恭喜您获得${this.random}件商品折上再减`
			            });
			            this.$store.dispatch('getUserInfo');
			        })
			}
			
			this.initPage();
			
			// 计算剩余时间
			let endTime = moment().format('YYYY-MM-DD 23:59:59');
			let startTime = moment().format('YYYY-MM-DD HH:mm:ss');
			let daysLeft = moment(endTime).diff(startTime, 'days');
			let hoursLeft = moment(endTime).diff(startTime, 'hours') - daysLeft * 24;
			let minutesLeft =
				moment(endTime).diff(startTime, 'minutes') -
				daysLeft * 24 * 60 -
				hoursLeft * 60;
			let secondsLeft =
				moment(endTime).diff(startTime, 'seconds') -
				daysLeft * 24 * 60 * 60 -
				hoursLeft * 60 * 60 -
				minutesLeft * 60;
			this.couponTime = [daysLeft, hoursLeft, minutesLeft, secondsLeft];
			
			my.reportAnalytics('enter_baiyibutie', {
				desc: '进入百亿补贴页'
			});
			
			if (options && options.source === 'webview') {
				this.$service.million.redEnvelopeRainRecord.statisticsClickData({
					isBybt: true,
					type: 4
				});
			}
        },
		onShow() {
			if (this.isFirstEnter) {
				this.$store.dispatch('getUserInfo');
			}
			this.isFirstEnter = true;
		},
		onHide() {
			my.reportAnalytics('bg_baiyibutie', {
				desc: '离开百亿补贴页'
			});
		},
        computed: {
            ...mapGetters(['userInfo', 'conf', 'token', 'app', 'hdyxRiskSetting']),
        },
        methods: {
            initPage() {
                uni.showLoading({
                    title: '加载中...'
                });
				this.tabList = [];
                this.$service.million.specialClassify
                    .list({
                        specialType: 100,
                        isBybt: true
                    })
                    .then(res => {
                        res.forEach(item => {
                            item.label = item.mainName;
                          	item.loading = false;
                          	item.finished = false;
                          	item.error = false;
                          	item.empty = false;
                          	item.page = 1;
                          	item.list = [];
                        });
                        this.tabList = this.tabList.concat(res);

                        this.loadMore(this.tabList[0]);
						
						this.$store.dispatch('addVisitRecordZfb', { pageType : 5, floorId : this.tabList[0].floorId });
                    });
            },
            beforeLoader(item) {
                this.params.floorId = item.floorId;
                this.params.isBybt = true;
                this.params.type = 3;
                this.params.sort = 'desc';
                this.params.order = 'zfbLevel';
                this.service = this.$service.million.bwbtGoods.list(this.params);
                return true;
            },
			onCopySuccess(tkl, refresh) {
				my.navigateToMiniProgram({
					appId: '2018091261350219',
					path: `/pages/h5pages/h5pages?targetURI=${tkl}`
				});
				
				if (refresh) {
					setTimeout(() => {
						this.onRefresh(this.tabList[this.active]);
					}, 2000)
				}
			},
			tabChangeCustom(index) {
				this.tabChange(index);
				this.$store.dispatch('addVisitRecordZfb', { pageType : 5, floorId : this.tabList[index].floorId });
				if (index <= 4) {
					my.reportAnalytics('click_fenlei' + (index + 1), {
						desc: '点击第' + this.toChineseNum(index + 1) + '个商品类目'
					});
				}
			},
			touchStart(e) {
				this.startCoor = e.touches[0].pageX;
			},
			touchEnd(e) {
				if (this.startCoor > e.changedTouches[0].pageX) {
					if ((this.startCoor - e.changedTouches[0].pageX) > 150) {
						if (this.active === (this.tabList.length - 1)) {
							this.$refs.tab.tabChange(0);
						} else {
							this.$refs.tab.tabChange(this.active + 1)
						}
					}
				} else {
					if ((e.changedTouches[0].pageX - this.startCoor) > 150) {
						if (this.active === 0) {
							this.$refs.tab.tabChange(this.tabList.length - 1);
						} else {
							this.$refs.tab.tabChange(this.active - 1);
						}
					}
				}
			}
        },
		onShareAppMessage() {
			const { shareFriendMainTemplate, shareFriendMainSubtitleTemplate, shareImageUrl } = this.conf;

			return {
				title: shareFriendMainTemplate,
				content: shareFriendMainSubtitleTemplate,
				desc: shareFriendMainSubtitleTemplate,
				path: '/pages/index/index',
				bgImgUrl: shareImageUrl || 'https://onecode-zfx-one.oss-cn-shenzhen.aliyuncs.com/20200921/919c9340-fbed-11ea-805b-2132711803c2.png',
				success: () => {
					if (this.hdyxRiskSetting.shareIconDisplay === 1) {
						this.$service.million.bwbtUser.shareBwbt({
							isBybt: true
						}).then(() => {
							this.$service.million.winners.getSubsidiesAmount({
								isBybt: true
							}).then(res => {
								this.$store.dispatch('getUserInfo');
							});
						});
					}
				}
			};
		},
    }
</script>

<style lang="scss" scoped>
.content {
	.header {
		width: 100%;
		height: 292rpx;
		background: #4BA1FE;
		.title-share {
			color: #fff;
			font-size: 30rpx;
			padding-left: 40rpx;
			padding-top: 78rpx;
			@include flexBox(space-between);
			.title {
				font-size: 30rpx;
			}
		}
		.amount-time {
			color: #fff;
			padding: 0 18rpx 0 40rpx;
			margin-top: 30rpx;
			font-size: 24rpx;
			@include flexBox(space-between, flex-end);
			.left {
				@include flexBox(center, flex-end);
			}
			.right {
				@include flexBox();
			}
		}
	}
	.balance-sticky {
		background: #4BA1FE;
		width: 100%;
		height: 112rpx;
		color: #fff;
		font-size: 26rpx;
		position: fixed;
		top: -112rpx;
		transition: 0.5s;
		z-index: 100;
		@include flexBox(space-between, center);
		&.active {
			top: 0;
		}
		.left {
			@include flexBox(flex-start, center);
			margin-left: 28rpx;
			.cash {
				margin-right: 20rpx;
				@include flexBox(flex-start, center);
			}
			.text {
				margin-right: 4rpx;
			}
		}
	}
	.share {
		font-size: 26rpx;
		height: 52rpx;
		background: #0B54BA;
		border-radius: 50rpx 0 0 50rpx;
		padding: 0 10rpx 0 20rpx;
		color: #fff;
		border: none;
		@include flexBox(center, center);
		&::after {
			border: none;
		}
		.iconfont {
			margin-right: 6rpx;
		}
	}
	.goods-list {
		.skeleton-wrap {
			background: #fff;
			width: 704rpx;
			margin: 0 auto;
			margin-top: 20rpx;
			border-radius: 16rpx;
		}
	}
	.balance-popup {
		border-radius: 16rpx 16rpx 0 0;
		background: #f24e36;
		padding: 30rpx;
		position: relative;
		@include flexBox(center, center, column)
		.icon-guanbi {
			position: absolute;
			right: 10rpx;
			top: 10rpx;
			color: #fff;
		}
		.title,
		.money {
			text-align: center;
			color: #fae480;
		}
		.title {
			font-size: 30rpx;
			margin-bottom: 30rpx;
		}
		.money {
			font-size: 34rpx;
		}
		.btn {
			width: 400rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			color: #f24938;
			margin: 0 auto;
			margin-top: 50rpx;
			border-radius: 50rpx;
			font-size: 28rpx;
		}
		.share {
			background-image: linear-gradient(to bottom, #ffed93, #fdb626);
		}
		.do {
			border: 2rpx solid #fc9481;
			color: #ffd1a3;
		}
	}
}
</style>